package com.jerry.hm.datastructure.priorityqueue;

import com.jerry.hm.datastructure.queue.Queue;

/**
 * 基于有序数组实现优先级队列
 *
 * @author Jerry
 * @since 2024/10/5 12:24
 */
public class PriorityQueue2<E extends Priority> implements Queue<E> {

    private Priority[] array;
    private int size;

    public PriorityQueue2(int capacity) {
        array = new Priority[capacity];
    }

    /**
     * 向队尾插入元素
     *
     * @param e
     * @return
     */
    @Override
    public boolean offer(E e) {
        if (isFull()) {
            return false;
        }
        insert(e);
        size++;
        return true;
    }

    /**
     * 从队首移除元素
     *
     * @return
     */
    @Override
    public E poll() {
        if (isEmpty()) {
            return null;
        }
        E e = (E) array[size - 1];
        array[--size] = null;
        return e;
    }

    /**
     * 从队首获取元素
     *
     * @return
     */
    @Override
    public E peek() {
        if (isEmpty()) {
            return null;
        }
        return (E) array[size - 1];
    }

    /**
     * 队列是否空
     *
     * @return
     */
    @Override
    public boolean isEmpty() {
        return size == 0;
    }

    /**
     * 队列是否满
     *
     * @return
     */
    @Override
    public boolean isFull() {
        return size == array.length;
    }

    /**
     * 插入元素
     *
     * @param e
     */
    private void insert(E e) {
        int i = size - 1;
        while (i >= 0 && array[i].priority() > e.priority()) {
            array[i + 1] = array[i];
            i--;
        }
        array[i + 1] = e;
    }
}